package com.tn.wservice.validator;

import java.util.ArrayList;
import java.util.List;

import com.tn.wservice.validator.IValidationResult.Result;
import com.tn.wservice.validator.NumericComparisonValidation.Operator;

public class NumericCompareValidator implements IValidator {

	private List<NumericComparisonValidation> validations = new ArrayList<NumericComparisonValidation>();

	@Override
	public IValidationResult validate(Object businessObject) throws Exception {
		ValidationResultImp resultImp = new ValidationResultImp();

		for (NumericComparisonValidation validation : this.getValidations()) {
			Operator operator = validation.getOperator();
			Number lhsValue = validation.getLhsValueGenerator().getValue(
					businessObject);
			Number rhsValue = validation.getRhsValueGenerator().getValue(
					businessObject);

			boolean result = evaluate(lhsValue, rhsValue, operator);
			if (!result) {
				resultImp.setResult(Result.FAILURE);
				resultImp.addErrorMsg(validation.getErrorMsg());
			}
		}
		return resultImp;
	}

	private boolean evaluate(Number lhsValue, Number rhsValue, Operator operator) {
		boolean result = false;
		switch (operator) {
		case GTE:
			result = lhsValue.doubleValue() >= rhsValue.doubleValue();
			break;
		case GT:
			result = lhsValue.doubleValue() > rhsValue.doubleValue();
			break;
		case LTE:
			result = lhsValue.doubleValue() <= rhsValue.doubleValue();
			break;
		case LT:
			result = lhsValue.doubleValue() < rhsValue.doubleValue();
			break;
		case EQ:
			result = lhsValue.doubleValue() == rhsValue.doubleValue();
			break;
		default:
			return false;
		}

		return result;
	}

	public void setValidations(List<NumericComparisonValidation> validations) {
		this.validations = validations;
	}

	public List<NumericComparisonValidation> getValidations() {
		return validations;
	}

}
